#!/usr/bin/python
"""
This script calculates average min distance between proteins in xyz file
"""

__author__ = 'Mateusz Lis'
__version__ = '0.1'

from constants import R, T
import math
from optparse import OptionParser
import sys
from time import time
from utils import distance
from structures.xyzfile import XYZFile 


def main(argv=None):
    global options 
    options = parseCommandLine()

    startTime = time()

    fIn = options.xyzFilename
    fOut = options.datFilename
    outList = []

    xyzFile = XYZFile(fIn)
    frame = xyzFile.nextFrame()
    i = 0
    with open( fOut, 'w' ) as datFile:
        while frame is not None:
            proteins = []
            for atom in frame.atoms:
                if atom.symbol == "PROTEIN":
                    proteins.append(atom)
            print "Found proteins", i

            proteinDistances = [(prot, calcDist(prot, proteins)) for prot in proteins]
            print "Calc distances", i
            centralProts = [prot for prot, _ in \
                    sorted(proteinDistances, key=lambda protDist: protDist[1])[:len(proteins)/7]]
            print "Central points", i
            distSum = 0

            for protein in centralProts:
                distSum += sum([distance([protein.x,protein.y], [b.x, b.y]) for b in centralProts])

            print "Result", i, distSum
            datFile.write("%u %s" % (i, distSum))
            i += 1
            frame = xyzFile.nextFrame()


    if options.verbose:
        print "Execution time", time() - startTime

def calcDist(atom, atoms):
    distances = [distance([atom.x, atom.y], [second.x, second.y]) for second in atoms]
    distances.sort()
    return sum(distances[:7])
    
def parseCommandLine():
    """
    Sets up command line arguments and parses them
    """
    parser = OptionParser(usage="%prog ", version="%prog " + __version__,
                          description='''
This script calculates average min distance between proteins in xyz file
    ''')
    parser.add_option("-f", "--xyz", dest="xyzFilename", default="traj.xyz",
    help="XYZ trajectory (default traj.xyz)", metavar="XYZFILE")
    parser.add_option("-o", "--output", dest="datFilename", default="prot_distance.dat",
    help='Output file name', metavar="DATFILE")
    parser.add_option("-q", "--quiet",
    action="store_false", dest="verbose", default=True,
    help="don't print status messages to stdout")

    (options, _) = parser.parse_args()

    return options
    

if __name__ == "__main__":
    sys.exit(main())
